<?php
/**
 * Controller_Posts 日志管理
 *
 * @package Movoin Blog
 * @subpackage Admin
 *
 */

//{{include
FLEA::loadClass('Controller_Base');
//}}

class Controller_Posts extends Controller_Base
{

	/**
	 * 日志模型
	 *
	 * @var object
	 */
    var $modelPost;

    /**
     * 日志分类模型
     *
     * @var object
     */
    var $modelCategories;

    /**
     * 构造函数
     *
     * @return Controller_Posts
     */
    function Controller_Posts()
    {
        // 构造父类
        parent::Controller_Base();
        // 日志模型
        $this->modelPost = & FLEA::getSingleton('Model_Posts');
        // 分类模型
        $this->modelCategories = & FLEA::getSingleton('Model_Categories');
    }

    /**
     * 所有日志
     */
    function actionIndex()
    {
    	/**
    	 * Get parmes
    	 */
        $page = isset($_GET['page'])?(int)$_GET['page']:0;
        $date = isset($_GET['date'])?trim($_GET['date']):null;
        $cate = isset($_GET['cate_id'])?(int)$_GET['cate_id']:null;
        $status = isset($_GET['status'])?trim($_GET['status']):null;
        /**
         * Query Condition
         */
        $where = null;
        if($date) {
        	$where[] = array('post_date', $date);
        }
        if($cate) {
        	$where[] = array('cate_id', $cate);
        }
    	if($status) {
        	$where[] = array('status', $status);
        }
        /**
         * Load FLEA_Helper_Pager Helper Class
         */
        FLEA::loadHelper('pager');
        $pagesize = 15;
        $table =& $this->modelPost->getTable();
        $table->disableLinks(array('comments','attach'));
        $pager =& new FLEA_Helper_Pager($table, $page, $pagesize, $where, 'created DESC, post_id DESC');
        $this->_tpl->assign('posts', $pager->findAll('post_id,title,cate_id,comment_count,view_count,created,status'));
        $this->_tpl->assign('pager', $pager->getPagerData());
        /**
         * Load FLEA_Helper_Array array function
         */
        FLEA::loadHelper('array');
        $cates = $this->modelCategories->getCategories('cate_id,name');
        $cates = array_to_hashmap($cates, 'name', 'cate_id');
        $baseCate = array('View all categories' => 0);
        $cates = array_merge($baseCate, $cates);
        $this->_tpl->assign('cates',$cates);
		/**
         * Set Archives
         */
		$archives = $this->modelPost->getArchives();
		$dates = array_to_hashmap($archives, 'name', 'value');
		$baseDate = array('Show all dates' => '');
		$dates = array_merge($baseDate, $dates);
		$this->_tpl->assign('dates',$dates);
		/**
		 * Set Posts Count
		 */
		$postsCount = array(
		    'all' => $this->modelPost->getCount(),
		    'publish' => $this->modelPost->getCount('publish'),
		    'draft' => $this->modelPost->getCount('draft')
		);
		$this->_tpl->assign('postsCount', $postsCount);
        /**
         * Display
         */
        $this->_tpl->display('posts.html');
    }

    /**
     * 发表新日志
     *
     */
    function actionNew()
    {
        $table = & $this->modelPost->getTable();
        $data = $this->_prepareData($table->meta);
        $this->_editPost($data);
    }

    /**
     * 保存日志
     *
     */
    function actionSavePost()
    {
        //dump($this->_processTags(&$_POST));
        js_alert($this->modelPost->savePost(&$_POST), 0, url('posts'));
    }

    function _processTags(& $row) {
        // 读出数据库现有的所有 tags
        $tableTags =& FLEA::getSingleton('Table_Tags');
        $tableTags->disableLink('posts');
        /* @var $tableTags Table_Tags */
        $rowset = $tableTags->findAll(null);

        /**
         * 将记录集转换为名值对
         */
        FLEA::loadHelper('array');
        $existsTags = array_to_hashmap($rowset, 'label');

        // 处理用户输入的 tags
        $labels = explode(' ', $row['tags']);
        array_remove_empty($labels);

        // 载入汉字转拼音助手
        FLEA::loadFile('Helper_pinyin');
        $tags = array();
        foreach ($labels as $label) {
            $label = strtolower($label);
            if (isset($existsTags[$label])) {
                // 将日志登记到现有 tag
                $existsTags[$label]['post_count'] = $existsTags[$label]['post_count'] + 1;
                $tags[] = $existsTags[$label];
            } else {
                // 创建新 tag，并登记日志
                $pinyin = is_null(Pinyin($label))?trim(Pinyin($label)):$label;
                $tags[] = array('label' => $label, 'slug' => $pinyin);
            }
        }

        $row['tags'] = $tags;
        return $row;
        //return true;
    }
	/**
	 * 日志分类列表
	 *
	 */
    function actionCategories()
    {
        $list = $this->modelCategories->getCategories('cate_id,name,slug,description,post_count');
        $this->_tpl->assign('list',$list);
        $this->_tpl->display('categories.html');
    }

    /**
     * 修改日志分类
     *
     */
    function actionEditCategory()
    {
        $cate_id = $_GET['cate_id']?(int)$_GET['cate_id']:null;
        $data = $this->modelCategories->getCategory($cate_id,'cate_id,name,slug,keywords,description,sort_id');
        $this->_tpl->assign('cate',$data);
        $this->_tpl->display('edit-category.html');
    }

    /**
     * 创建日志分类
     *
     */
    function actionCreateCategory()
    {
        js_alert($this->modelCategories->createCategory(&$_POST),0,url('posts','categories'));
    }

    /**
     * 保存日志分类修改
     *
     */
    function actionSaveCategory()
    {
        js_alert($this->modelCategories->updateCategory(&$_POST),0,url('posts','categories'));
    }

    /**
     * 删除日志分类
     *
     */
    function actionRemoveCategory()
    {
        $cate_id = $_GET['cate_id']?(int)$_GET['cate_id']:null;
        js_alert($this->modelCategories->removeCategory($cate_id), 0, url('posts','categories'));
    }

    /**
     * 日志分类批量管理方法
     *
     * delete: 批量删除
     * publish: 批量发布
     *
     */
    function actionCateMan()
    {
        $_action = $_POST['actions']?trim($_POST['actions']):null;
        if($_action=='delete'){
            js_alert($this->modelCategories->removeCategories($_POST['checkid']), 0, url('posts','categories'));
        }
        redirect(url('posts','categories'));
    }

    function actionUploader()
    {
    	$this->_tpl->display('editor.uploader.html');
    }

    /**
     * 标签列表
     *
     */
    function actionTags()
    {
        $this->_tpl->display('tags.html');
    }

    /**
     * 自动划出内容中的关键字
     *
     */
    function actionCheckTags()
    {
    	$contents = trim($_POST['content']);
        $tblTags =& FLEA::getSingleton('Table_Tags');
        $tagsList = $tblTags->findAll();
        if($tagsList){
            echo '<div class="tagslist clear_after">';
            foreach($tagsList as $tag){
            	if(stristr($contents, $tag['label'])) {
                    echo '<span>' . $tag['label'] . '</span>';
            	}
            }
            echo '</div>';
        } else {
            echo 'Null';
        }
        /**
         * Clear memory
         */
        $tagsList = array();
        unset($tagsList);
        unset($tblTags);
    }

    /**
     * 修改日志
     *
     * @param array $data
     */
    function _editPost(&$data)
    {
        FLEA::loadHelper('array');
        $cates = $this->modelCategories->getCategories('cate_id,name');
        $cates = array_to_hashmap($cates, 'name', 'cate_id');
        $this->_tpl->assign('cates',$cates);
        /**
         * Set add_js To Load BUEditor Javascript Librarys
         */
        FLEA::setAppInf('add_js',array('editor'=>'bueditor,library/functions'));
        $this->_tpl->assign('editorName','memo');// Set Editor's name
        $this->_tpl->assign('form',$data);
        $this->_tpl->display('edit-post.html');
    }

}
